<template>
    <div class="app-container">
      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="时间段" prop="query_time">
          <el-date-picker v-model="query_time" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="样本管理番号" prop="sampleName">
          <el-input v-model="queryParams.sampleCode" placeholder="请输入样本" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getSampleListByNameTime">搜索</el-button>
          <el-button type="primary" @click="resetButton">重置</el-button>
          <el-button type="warning" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" plain>新增</el-button>
        </el-col>
      </el-row>
  
      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%," height="600px">
        <el-table-column v-if="false" label="编号" prop="Id" align="center" />
        <el-table-column label="序号" prop="serial_number" align="center" />
        <el-table-column label="部门" prop="sys_deptId" align="center" />
        <el-table-column label="样本名称" prop="sampleName" align="center" />
        <el-table-column label="制作日期" prop="enter_time" align="center" />
        <el-table-column label="样本管理番号" prop="sampleCode" align="center" />
        <el-table-column label="制造承认人" prop="reviewer_idZ" align="center" />
        <el-table-column label="技术承认人" prop="reviewer_idJ" align="center" />
        <el-table-column label="品管承认人" prop="reviewer_idP" align="center" />
        <el-table-column label="最终承认人" prop="reviewer_idF" align="center" />
        <el-table-column label="制作人" prop="user" align="center" />
        <el-table-column label="有效月份" prop="validMonth" align="center" />
        <el-table-column label="有效期限" prop="end_time" align="center" />
        <el-table-column label="状态" prop="status" align="center">
          <template #default="scope">
            <span :class="'status-' + getStatusType(scope.row.end_time)">
              {{ scope.row.status }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" align="center">
  
          <template #default="scope">
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
  
      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getSampleList" />
      <!-- 新增表单 -->
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="部门" prop="sysDept">
            <treeselect v-model="form.sysDept" :options="treeData" :show-count="false" placeholder="请选择部门" />
          </el-form-item>
          <el-form-item label="样本名称" prop="sampleName">
            <el-input v-model="form.sampleName" placeholder="请输入样本名称" />
          </el-form-item>
          <el-form-item label="制作日期" prop="enterTime">
            <el-date-picker v-model="form.enterTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
              format="yyyy-MM-dd" />
          </el-form-item>
          <el-form-item label="样本编号" prop="sampleCode">
            <el-input v-model="form.sampleCode" placeholder="请输入样本编号" />
          </el-form-item>
          <el-form-item label="制造承认人" prop="reviewerZ">
            <el-input v-model="form.reviewerZ" placeholder="请输入制造承认人" />
          </el-form-item>
          <el-form-item label="技术承认人" prop="reviewerJ">
            <el-input v-model="form.reviewerJ" placeholder="请输入技术承认人" />
          </el-form-item>
          <el-form-item label="品管承认人" prop="reviewerP">
            <el-input v-model="form.reviewerP" placeholder="请输入品管承认人" />
          </el-form-item>
          <el-form-item label="最终承认人" prop="reviewerF">
            <el-input v-model="form.reviewerF" placeholder="请输入最终承认人" />
          </el-form-item>
          <el-form-item label="有效月份" prop="validityPeriod">
            <el-input-number @change="getEndTime()" v-model="form.validityPeriod" value="0" :min="0" :max="36"
              controls-position="right" />
            <span class="ml10">个月</span>
          </el-form-item>
          <el-form-item label="有效期限" prop="lastTime">
            <el-date-picker readonly v-model="form.lastTime" type="date" placeholder="选择日期" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
  
      <!-- 状态弹出 -->
      <el-dialog title="样本过期提醒" :visible.sync="showWarningDialog" width="600px" custom-class="warning-dialog"
        :show-close="false">
        <el-tabs type="border-card">
          <el-tab-pane label="临近过期">
            <el-table :data="warningData" height="250">
              <el-table-column prop="sampleCode" label="样本编号" />
              <el-table-column prop="lastTime" label="过期时间" />
              <el-table-column label="剩余天数">
                <template #default="scope">
                  {{ calcRemainDays(scope.row.lastTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="已过期">
            <el-table :data="expiredData" height="250">
              <el-table-column prop="sampleCode" label="样本编号" />
              <el-table-column prop="lastTime" label="过期时间" />
              <el-table-column label="过期天数">
                <template #default="scope">
                  {{ calcExpiredDays(scope.row.lastTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
  
        <div slot="footer">
          <el-button @click="showWarningDialog = false">关 闭</el-button>
        </div>
      </el-dialog>
  
    </div>
  </template>
  
  <script>
  import { listAllDept } from "@/api/system/dept";
  import { selectSample, selectSampleByNameTime, sampleExport, addSample, delSample, querySampleEndTime } from "@/api/sample/sampleAdd"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import Treeselect from "@riophae/vue-treeselect";
  import "splitpanes/dist/splitpanes.css";
  export default {
    name: "sample",
    components: { Treeselect },
    data() {
      return {
        //临期
        warningData: [],
        //过期
        expiredData: [],
        //提示弹出
        showWarningDialog: false,
        //查询用时间
        query_time: [],
        //部門列表
        deptList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sampleName: '',
          sampleCode: ''
        },
        // 部门选项
        treeData: undefined,
        // 表格数据
        tableData: [],
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        dialogVisible: false,
        // 表单数据
        form: {
  
        },
        // 表单验证规则
        rules: {
          sysDept: [{ required: true, message: "请选择部门", trigger: "blur" }],
          sampleName: [
            { required: true, message: "样本名称不能为空", trigger: "blur" },
          ],
          enterTime: [
            { required: true, message: "请选择制作日期", trigger: "blur" },
          ],
          sampleCode: [
            { required: true, message: "样本编号不能为空", trigger: "blur" },
          ],
          reviewerZ: [
            { required: true, message: "请输入承认人", trigger: "blur" },
          ],
          reviewerJ: [
            { required: true, message: "请输入承认人", trigger: "blur" },
          ],
          reviewerP: [
            { required: true, message: "请输入承认人", trigger: "blur" },
          ],
          reviewerF: [
            { required: true, message: "请输入承认人", trigger: "blur" },
          ],
          validity_period: [
            { required: true, message: "请选择有效时间", trigger: "change" },
          ]
        },
      };
    },
    created() {
      this.getalllist();
      this.getwarningexpiredData();
    },
    methods: {
      getalllist() {
        listAllDept().then(response => {
          let deptList = response.data;
          const nodeMap = new Map();
          const rootNodes = [];
          // 创建节点映射
          deptList.forEach(dept => {
            nodeMap.set(dept.deptId, {
              id: dept.deptId,
              label: dept.deptName,
              children: []
            });
          });
  
          // 构建树结构
          deptList.forEach(dept => {
            const node = nodeMap.get(dept.deptId);
            const parentId = dept.parentId;
  
            if (parentId && nodeMap.has(parentId)) {
              nodeMap.get(parentId).children.push(node);
            } else {
              rootNodes.push(node);
            }
          });
          this.treeData = this.clearChildren(rootNodes);
        })
      },
      clearChildren(nodes) {
              return nodes.map(node => {
                  const nodeC = { ...node }
                  if (nodeC.children && nodeC.children.length > 0) {
                      nodeC.children = this.clearChildren(nodeC.children);
                  } else {
                      delete nodeC.children;
                  }
                  return nodeC
              })
          },
      //excel使用
      handleExport() {
        this.$confirm("确认导出用户数据吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // 调用导出接口
          sampleExport().then(response => {
            const url = URL.createObjectURL(new Blob([response]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', '样品数据.xlsx');
            document.body.appendChild(link);
            link.click();
          });
        });
      },
      //查询样本
      getSampleList() {
        this.tableData = [];
        selectSample(this.queryParams.pageNum, this.queryParams.pageSize).then(response => {
          this.total = response.total;
          for (let index = 0; index < response.list.length; index++) {
            const element = response.list[index];
            const enter_time = new Date(element.enterTime);
            const end_time = new Date(element.lastTime);
            this.tableData.push(
              {
                Id: element.id,
                serial_number: index + 1,
                sys_deptId: element.sysDept.deptName,
                sampleName: element.sampleName,
                sampleCode: element.sampleCode,
                reviewer_idZ: element.reviewerZ,
                reviewer_idJ: element.reviewerJ,
                reviewer_idP: element.reviewerP,
                reviewer_idF: element.reviewerF,
                validMonth: element.validityPeriod,
                enter_time: this.formatDate(enter_time),
                end_time: this.formatDate(end_time),
                user: element.user,
                status: this.getCNstatus(end_time)
              })
          }
        })
      },
      //条件查询样本
      getSampleListByNameTime() {
        this.tableData = [];
        // alert(JSON.stringify(this.queryParams.pageNum))
        selectSampleByNameTime(this.queryParams.pageNum, this.queryParams.pageSize, this.queryParams.sampleCode, this.query_time[0], this.query_time[1]).then(response => {
          this.total = response.total;
          for (let index = 0; index < response.list.length; index++) {
            const element = response.list[index];
            const enter_time = new Date(element.enterTime);
            const end_time = new Date(element.lastTime);
            this.tableData.push(
              {
                Id: element.id,
                serial_number: index + 1,
                sys_deptId: element.sysDept.deptName,
                sampleName: element.sampleName,
                sampleCode: element.sampleCode,
                reviewer_idZ: element.reviewerZ,
                reviewer_idJ: element.reviewerJ,
                reviewer_idP: element.reviewerP,
                reviewer_idF: element.reviewerF,
                validMonth: element.validityPeriod,
                enter_time: this.formatDate(enter_time),
                end_time: this.formatDate(end_time),
                user: element.user,
                status: this.getCNstatus(end_time)
              })
          }
        })
      },
      //重置
      resetButton() {
        this.query_time = [];
        this.queryParams.sampleCode = '';
      },
      //状态自动转换
      getCNstatus(end_time) {
        const nowTime = new Date();
        const lastTime = end_time - nowTime;
        if (lastTime > 2592000000) {
          return '正常'
        } else if (lastTime > 0) {
          return '临近过期'
        } else {
          return '已过期';
        }
      },
  
      /** 查询部门下拉树结构 */
  
      //改变结束时间
      getEndTime() {
        this.form.lastTime = this.calculateNewDate(this.form.enterTime, this.form.validityPeriod)
      },
      // 核心计算逻辑
      calculateNewDate(data, addMonth) {
        if (!data || !addMonth) return
        const originalDate = new Date(data);
        originalDate.setDate(originalDate.getDate() - 1);
        const originalYear = originalDate.getFullYear()
        const originalMonth = originalDate.getMonth()
        const originalDay = originalDate.getDate()
  
        // 计算新日期
        const totalMonths = originalMonth + addMonth
        const newYear = originalYear + Math.floor(totalMonths / 12)
        const newMonth = totalMonths % 12
  
        // 创建临时日期检测月末
        const tempDate = new Date(newYear, newMonth + 1, 0) // 下个月的第0天即本月最后一天
        const lastDayOfNewMonth = tempDate.getDate()
  
        // 调整日期（处理类似1月31日+1个月的情况）
        const adjustedDay = Math.min(originalDay, lastDayOfNewMonth)
  
        // 生成最终日期
        const finalDate = new Date(newYear, newMonth, adjustedDay)
        return this.formatDate(finalDate)
      },
  
      // 日期格式化
      formatDate(date) {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
      },
      // 重置按钮
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 新增按钮
      handleAdd() {
        this.dialogVisible = true;
        // 清空表单
        this.form = {
          enterTime: new Date().toISOString().split('T')[0] // 直接使用ISO格式日期
        };
        this.title = "新增样本";
      },
      // 编辑按钮
      handleEdit(row) {
        this.resetForm();
        this.form = Object.assign({}, row);
        this.open = true;
        this.title = "修改样本";
      },
      // 删除按钮
      handleDelete(row) {
        this.$confirm('确认删除该样本？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delSample(row.Id).then(response => {
              if (response > 0) {
                this.$message.success("删除成功");
                this.getSampleList();
              } else {
                this.$message.success("删除失败");
              }
            })
          })
          .catch(() => { });
      },
      // 表单提交
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            addSample(this.form).then(response => {
              if (response === '添加成功') {
                this.$message.success(response);
                this.getSampleList();
              } else {
                this.$message.error(response);
              }
            })
            this.dialogVisible = false;
          }
        });
      },
      // 取消按钮
      cancel() {
        this.dialogVisible = false;
        this.resetForm();
      },
      // 重置表单
      resetForm() {
        this.form = {
  
        };
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      },
      //關閉表單
      handleClose() {
        this.dialogVisible = false;
      },
      //状态类型判断方法
      getStatusType(endTime) {
        const now = new Date();
        const endDate = new Date(endTime);
        const diff = endDate - now;
        if (diff > 2592000000) { // 30天
          return 'normal';
        } else if (diff > 0) {
          return 'warning';
        } else {
          return 'expired';
        }
      },
      // 计算剩余天数
      calcRemainDays(endTime) {
        const diff = new Date(endTime) - new Date()
        return Math.ceil(diff / (1000 * 3600 * 24))
      },
  
      // 计算过期天数
      calcExpiredDays(endTime) {
        const diff = new Date() - new Date(endTime)
        return Math.floor(diff / (1000 * 3600 * 24))
      },
      //拿到临期和过期
      getwarningexpiredData() {
        querySampleEndTime().then(response => {
          for (let index = 0; index < response.length; index++) {
            const element = response[index];
            if (this.getStatusType(element.lastTime) === 'warning') {
              this.showWarningDialog = true;
              this.warningData.push(element);
            } else if (this.getStatusType(element.lastTime) === 'expired') {
              this.showWarningDialog = true;
              this.expiredData.push(element);
            }
          }
        })
      }
    },
  
    mounted() {
      this.getSampleList();
    },
  };
  </script>
  
  <style scoped>
  .ml10 {
    margin-left: 10px;
  }
  
  /* 状态样式 */
  .status-normal {
    color: #67C23A;
    background: #f0f9eb;
    padding: 5px 10px;
    border-radius: 4px;
    display: inline-block;
  }
  
  .status-warning {
    color: #E6A23C;
    background: #fdf6ec;
    padding: 5px 10px;
    border-radius: 4px;
    display: inline-block;
  }
  
  .status-expired {
    color: #F56C6C;
    background: #fef0f0;
    padding: 5px 10px;
    border-radius: 4px;
    display: inline-block;
  }
  </style>